from Path import *

import os, csv

class NameFactory:
	def __init__(self, csv_files_dirs, latitude_column_index, longitude_column_index):
		# get the list of all files passed directly or contained in passed directories
		self.csv_files = []
		#self.paths = []
		self.latitude_column_index = latitude_column_index
		self.longitude_column_index = longitude_column_index
		
		for file_or_dir_name in csv_files_dirs:
                    if (not os.path.isfile(file_or_dir_name)):
                        raise NameError, "file or directory %s doesn't exist" % file_or_dir_name
		    if (os.path.isdir(file_or_dir_name)):
		        dir_files = os.listdir(file_or_dir_name)
		        for filename_in_dir in dir_files:
        			self.csv_files.append(os.path.realpath(file_or_dir_name + os.sep + filename_in_dir))
		    elif (os.path.isfile(file_or_dir_name)):
		        self.csv_files.append(os.path.realpath(file_or_dir_name))
		     
	def extractPaths(self):
		paths = []
	   	for filename in self.csv_files:
                        # deduce csv format
                        csvfile = open(filename, 'rb')
                        dialect = csv.Sniffer().sniff(csvfile.read(4096))
                        csvfile.seek(0)               
                        # create a csv file reader
	    		reader = csv.reader(csvfile, dialect)
                                       
			# create and fill a list of longiture and latitude pairs
	    		list = []
	    		reader.next()

                        for row in reader:
	    			lat, lng = float(row[self.latitude_column_index ][:-1]), float(row[self.longitude_column_index][:-1])
				pair = -lng, lat
			#	print pair
	       			list.append(pair)

	       		p = Path(filename, list)
	       		paths.append(p)
	       	return paths
	       	
	       	
       	
